/**
 * console  
 */

layui.define(function(exports) {
  /*
    下面通过 layui.use 分段加载不同的模块，实现不同区域的同时渲染，从而保证视图的快速呈现
  */
  //区块轮播切换
  layui.use(['admin', 'carousel', 'baseMethods'], function() {
    const {$, carousel, device, baseMethods} = layui;
    const pageData = {
      getUser() {
        const user = AppGeneral.getSystemUser();
        $('#admin-user-login-info').html(`<tr>
                  <th>账号</th>
                  <th>${user.userName||'--'}</th>
                </tr>
                <tr>
                  <th>IP</th>
                  <th>${user.ip||'--'}</th>
                </tr>
                <tr>
                  <th>地址</th>
                  <th>${user.ipAddress||'--'}</th>
                </tr>
                <tr>
                  <th>登陆时间</th>
                  <th>${user.loginTime||'--'}</th>
                </tr>`);
        $('.admin-user-welcome').html(`您好！<span>${user.displayName||''}</span>`);
        $('.admin-user-headimg').find('img').attr('src', AppGeneral.storage(user.avatar));
      },
      getData() {
        const localData = JSON.parse(sessionStorage.getItem('SYSTEM_COUNT'));
        if (localData) {
          return this.tplData(localData);
        }
        baseMethods.request({
          url: '/count',
          done: function (result) {
            if (result.code === 200) {
              sessionStorage.setItem('SYSTEM_COUNT', JSON.stringify(result.data));
              pageData.tplData(result.data);
            }
          }
        });
      },
      tplData(data) {
        const {dataCounts, widgetConfig} = data;
        const shortcut = [
          [
            {
              "title": "管理员",
              "url": "system/user/index",
              "icon": "layui-icon-user"
            },
            {
              "title": "角色管理",
              "url": "system/role/index",
              "icon": "layui-icon-group"
            },
            {
              "title": "日志管理",
              "url": "maintain/logs/activity/index",
              "icon": "layui-icon-log"
            },
            {
              "title": "系统设置",
              "url": "system/config/index",
              "icon": "layui-icon-set-fill"
            }
          ]
        ];
        $('.layadmin-shortcut div').html(`${shortcut.map(item => {
          return `<ul class="layui-row layui-col-space10">
            ${item.map(value => {
              return `<li class="layui-col-xs3"><a ${!value.url ? '' : 'lay-href="'+ value.url +'"'}><i class="layui-icon ${value.icon}"></i><cite>${value.title}</cite></a></li>`;
            }).join('')}
          </ul>`;
        }).join('')}`);

        if (dataCounts) {
          $('.layadmin-backlog div').html(`${dataCounts.map(item => {
            return `<ul class="layui-row layui-col-space10">
              ${item.map(value => {
                return `<li class="layui-col-xs6"><a ${!value.url?'':'lay-href="'+value.url+'"'} class="layadmin-backlog-body"><h3>${value.title}</h3><p><cite>${value.count||0}</cite></p></a></li>`;
              }).join('')}
            </ul>`;
          }).join('')}`);
        }

        if (widgetConfig) {
          $('#widget_config').html(`${widgetConfig.map(item => {
            return `<tr><th>${item[0]}</th><th>${item[1]}</th><th>${item[2]}</th></tr>`
          }).join('')}`);
        }

        //轮播切换
        $('.layadmin-carousel').each(function(){
          const othis = $(this);
          carousel.render({
            elem: this,
            width: '100%',
            arrow: 'none',
            interval: othis.data('interval'),
            autoplay: othis.data('autoplay') === true,
            trigger: (device.ios || device.android) ? 'click' : 'hover',
            anim: othis.data('anim')
          });
        });
      },
    }
    pageData.getUser();
    pageData.getData();
  });

  //数据概览
  layui.use(['admin', 'carousel', 'echarts', 'baseMethods'], function() {
    const {$, admin, carousel, echarts, baseMethods} = layui;
    baseMethods.request({
      url: '/line_chart',
      done: function (result) {
        if (result.code === 200) {
          lineChart(result.data);
        }
      }
    })
    function lineChart(data) {
      let options = [{
          title: {
            text: '一周流量趋势',
            x: 'center',
            textStyle: {
              fontSize: 14
            }
          },
          tooltip : {
            trigger: 'axis'
          },
          legend: {
            data:['','']
          },
          xAxis : [{
            type : 'category',
            boundaryGap : false,
            data: data.platform.keys||[]
          }],
          yAxis : [{
            type : 'value'
          }],
          series : [{
            name:'PV',
            type:'line',
            smooth:true,
            itemStyle: {normal: {areaStyle: {type: 'default'}}},
            data: data.platform.pv||[]
          },{
            name:'UV',
            type:'line',
            smooth:true,
            itemStyle: {normal: {areaStyle: {type: 'default'}}},
            data: data.platform.uv||[]
          }]
        }, {
          title : {
            text: '访客浏览器分布',
            x: 'center',
            textStyle: {
              fontSize: 14
            }
          },
          tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
          },
          legend: {
            orient : 'vertical',
            x : 'left',
            data: data.browser.keys||[]
          },
          series : [{
            name:'访问来源',
            type:'pie',
            radius : '55%',
            center: ['50%', '50%'],
            data: data.browser.data||[]
          }]
      }];
      let echartsApp = [],
          elemDataView = $('#LAY-index-dataview').children('div'),
          renderDataView = function(index) {
              echartsApp[index] = echarts.init(elemDataView[index], layui.echartsTheme);
              echartsApp[index].setOption(options[index]);
              //window.onresize = echartsApp[index].resize;
              admin.resize(function(){
                echartsApp[index].resize();
              });
          };
        //没找到DOM，终止执行
        if(!elemDataView[0]) return;
        renderDataView(0);
        //触发数据概览轮播
        let carouselIndex = 0;
        carousel.on('change(LAY-index-dataview)', function(obj){
          renderDataView(carouselIndex = obj.index);
        });
        //触发侧边伸缩
        admin.on('side', function(){
          setTimeout(function(){
            renderDataView(carouselIndex);
          }, 300);
        });
        //触发路由
        admin.on('hash(tab)', function(){
          layui.router().path.join('') || renderDataView(carouselIndex);
        });
    }
  });

  exports('console', {})
});